<template>
    <div class="my-rental-container">
      <el-card class="rental-list-card">
        <template #header>
          <div class="card-header">
            <span>我的租房</span>
            <el-button type="primary" @click="openMaintenanceStatusDialog">查看维修进度</el-button>
          </div>
        </template>
        
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>
        
        <div v-else-if="rentalList.length === 0" class="empty-container">
          <el-empty description="暂无租房信息" />
        </div>
        
        <div v-else class="house-list">
          <el-card
            v-for="rental in rentalList"
            :key="rental.rent_id"
            class="house-item"
            shadow="hover"
          >
            <div class="house-info">
              <el-image
                :src="formatImageUrl(rental.photo_url)"
                fit="cover"
                class="house-image"
              ></el-image>
              <div class="house-details">
                <h3>{{ rental.house_name }}</h3>
                <p>房东: {{ rental.landlord_name }}</p>
                <p class="price">¥{{ formatCurrency(rental.amount) }}/月</p>
                <p>起始日期: {{ formatDate(rental.start_date) }}</p>
                <p>结束日期: {{ formatDate(rental.end_date) }}</p>
              </div>
            </div>
            <div class="house-actions">
              <el-button type="primary" @click="showMaintenanceDialog(rental)">维修请求</el-button>
            </div>
          </el-card>
        </div>
      </el-card>
  
      <!-- 维修请求弹窗 -->
      <el-dialog
        v-model="maintenanceDialogVisible"
        title="提交维修请求"
        width="500px"
        center
      >
        <el-form :model="maintenanceForm" label-position="top">
          <el-form-item label="房屋名称">
            <el-input v-model="maintenanceForm.house_name" disabled />
          </el-form-item>
          <el-form-item label="维修内容描述" prop="description">
            <el-input
              v-model="maintenanceForm.description"
              type="textarea"
              :rows="4"
              placeholder="请详细描述需要维修的问题"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="maintenanceDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitMaintenance">提交</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 维修进度弹窗 -->
      <el-dialog v-model="maintenanceStatusVisible" title="维修进度" width="700px" center>
      <el-table :data="maintenanceStatusList" stripe style="width: 100%">
        <el-table-column prop="house_name" label="房屋名称" />
        <el-table-column prop="content" label="维修内容" />
        <el-table-column prop="submitted_at" label="申请时间" />
        <el-table-column prop="status" label="状态" />
        <el-table-column prop="processed_at" label="完成时间" />
        <el-table-column prop="result_notes" label="维修结果" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="maintenanceStatusVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from 'axios'
  
  // 响应式数据
  const loading = ref(true)
  const rentalList = ref([])
  const maintenanceDialogVisible = ref(false)
  const maintenanceForm = reactive({
    house_name: '',
    description: '',
    house_id: '',
    rent_id: '',
    landlord_id: ''
  })
  const currentRental = ref(null)
  const maintenanceStatusVisible = ref(false)
  const maintenanceStatusList = ref([])
  
  // 格式化货币
  const formatCurrency = (value) => {
    if (!value && value !== 0) return '-'
    return value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
  }
  
  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '未设置'
    const date = new Date(dateString)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }
  
  // 格式化图片URL
  const formatImageUrl = (url) => {
    if (!url) return 'https://via.placeholder.com/800x600?text=暂无图片'
    if (url.includes('house-img')) {
      const filename = url.split(/[/\\]/).pop()
      return `http://127.0.0.1:5000/static/house-img/${filename}`
    }
    return url
  }
  
  // 获取租房信息
  const fetchRentals = async () => {
    loading.value = true
    try {
      const response = await axios.get('http://127.0.0.1:5000/api/rent/rentList', {
        params: { tenant_id: localStorage.getItem('userId') },
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      
      if (response.data.status === 200) {
        rentalList.value = response.data.data
      } else {
        ElMessage.error(response.data.msg || '获取租房信息失败')
      }
    } catch (error) {
      console.error('获取租房信息失败:', error)
      ElMessage.error('获取租房信息失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }
  
  // 显示维修请求弹窗
  const showMaintenanceDialog = (rental) => {
    currentRental.value = rental
    maintenanceForm.house_name = rental.house_name
    maintenanceForm.house_id = rental.house_id
    maintenanceForm.rent_id = rental.rent_id
    maintenanceForm.landlord_id = rental.landlord_id
    maintenanceForm.description = ''
    maintenanceDialogVisible.value = true
  }
  
  // 提交维修请求
  const submitMaintenance = async () => {
    if (!maintenanceForm.description.trim()) {
      ElMessage.warning('请输入维修内容描述')
      return
    }
    
    try {
      const response = await axios.post('http://127.0.0.1:5000/api/rent/request', {
        tenant_id: localStorage.getItem('userId'),
        landlord_id: maintenanceForm.landlord_id,
        house_id: maintenanceForm.house_id,
        rent_id: maintenanceForm.rent_id,
        description: maintenanceForm.description,
        status: '待处理'
      }, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      
      if (response.data.status === 200) {
        ElMessage.success('维修请求提交成功')
        maintenanceDialogVisible.value = false
      } else {
        ElMessage.error(response.data.msg || '提交失败')
      }
    } catch (error) {
      console.error('提交维修请求失败:', error)
      ElMessage.error('提交失败，请稍后重试')
    }
  }
  
  // 维修查看进度
  const openMaintenanceStatusDialog = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/api/rent/maintenanceStatus', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    if (response.data.status === 200) {
      maintenanceStatusList.value = response.data.data
      maintenanceStatusVisible.value = true
    } else {
      ElMessage.error(response.data.msg || '获取维修记录失败')
    }
  } catch (error) {
    console.error('获取维修记录失败:', error)
    ElMessage.error('获取维修记录失败，请稍后重试')
  }
}

  onMounted(() => {
    fetchRentals()
  })
  
  // 暴露方法给父组件调用
  defineExpose({
    fetchRentals
  })
  </script>
  
  <style scoped>
  .my-rental-container {
    width: 100%;
  }
  
  .rental-list-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .loading-container, .empty-container {
    padding: 20px;
    text-align: center;
  }
  
  .house-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
    padding: 20px;
  }
  
  .house-item {
    border: 1px solid #ebeef5;
    transition: all 0.3s;
  }
  
  .house-item:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transform: translateY(-5px);
  }
  
  .house-info {
    cursor: pointer;
  }
  
  .house-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
  }
  
  .house-details {
    padding: 10px;
  }
  
  .house-details h3 {
    margin: 0 0 10px 0;
  }
  
  .house-details p {
    margin: 5px 0;
    color: #606266;
  }
  
  .price {
    color: #f56c6c;
    font-size: 18px;
    font-weight: bold;
  }
  
  .house-actions {
    padding: 10px;
    display: flex;
    justify-content: flex-end;
  }
  </style>